/**
 * 密码小键盘调用函数封装
 * 
 * @author 329202 <a href="mailto:fuyuxin@sf-express.com">符瑜鑫(Ricky Fu)</a>
 * @author 324945 <a href="mailto:fuyuxin@sf-express.com">戴桥斌(Andy Dai)</a>
 * 
 * @createDate 2012-06-28
 * @modifyDate 2012-07-20
 */
var PwdKeyBoard = null;

(function($){
	var $ocx = $([
			/*'<OBJECT classid="clsid:5BC1E7F5-23D7-477C-9B9D-F829B44FCE1C" codebase="js/keypad/YD736.ocx" style="HEIGHT: 500px;WIDTH:500px"></OBJECT>'	//二合一*/
			'<OBJECT classid="clsid:7AFCE07E-7B2C-4464-BA76-7466C4649A50" codebase="js/card/SFPayKeyBoard.ocx" style="HEIGHT: 500px;WIDTH:500px"></OBJECT>'	//USB
		].join('')), actX = $ocx.get(0);
	PwdKeyBoard = actX;
	var masterKey = null,workKey = null,execflag = false;
	/**
	 * 打开端口.
	 */
	var openCom = function() {
		var iRes = actX.IOpenCom(1, 9600);
		actX.ISetTimeout(15);// 设置串口超时，单位为秒
		if (iRes != 0) {
			alert("打开COM端口失败,错误码:" + iRes);
			return false;
		}
		return true;
	};

	/**
	 * 下载密钥.
	 */
	var downLoadKey = function() {
		
		masterKey = "0123456789ABCDEF0123456789ABCDEF";
		workKey = "0123456789ABCDEF9876549870ABCDEF";
		
		if(masterKey && workKey)
			return true;
		
		var flag = false;
		$.ajaxConnection(CONTEXT_PATH + "/securityKey/downloadKey", null, {
			// state 200
			success : function(data, textStatus) {
				if (data) {
					data = $.parseJSON(data);
					masterKey = data.masterKey;
					workKey = data.workKey;

					if (masterKey && workKey) {
						flag = true;
					} else {
						alert("密钥解析失败!");
						flag = false;
					}
				} else {
					alert("下载密钥失败!请确认您已登录!");
					return;
				}
			},
			// 404、500 e.g
			error : function(XMLHttpRequest, textStatus, errorThrown) {
				alert("网络异常!");
				return;
			}
		});

		return flag;
	};

	/**
	 * 下载主密钥.
	 */
	var downLoadMasterKey = function() {
		var iRes = actX.IDownLoadMasterKey(0, masterKey);
		if (iRes != 0) {
			alert("下载主密钥失败,错误码:" + iRes + ",请重试!");
			return false;
		}
		return true;
	};

	/**
	 * 下载工作密钥.
	 */
	var downLoadWorkKey = function() {
		var iRes = actX.IDownLoadWorkKey(0, 0, workKey);
		if (iRes != 0) {
			alert("下载工作密钥失败,错误码:" + iRes + ",请重试!");
			return false;
		}
		return true;
	};

	/**
	 * 工作密钥激活.
	 */
	var activeWorkKey = function() {
		var iRes = actX.ISetActiveWorkKey(0, 0);
		if (iRes != 0) {
			alert("工作密钥激活失败,错误码:" + iRes + ",请重试!");
			return false;
		}
		return true;
	};

	/**
	 * 关闭COM端口
	 */
	var closeCom = function() {
		var iRes = actX.ICloseCom();
		if (iRes != 0) {
			alert("关闭COM端口失败,错误码:" + iRes + ",请重试!");
			return false;
		}
		return true;
	};

	/**
	 * 设置工作加密模式
	 */
	var setWorkMode = function() {
		var iRes;
		iRes = actX.IKeypadWorkMode("2");
		if (iRes != 0) {
			alert("设置工作加密模式失败,错误码:" + iRes + ",请重试!");
			return false;
		}
		return true;
	};

	/**
	 * 读密码.
	 * 
	 * @param times
	 *            次数
	 */
	var readPwd = function(times) {
		var iRes;
		var iErr = "";
		try {
			if (!closeCom()) // 关闭COM端口
				return;
			if (!openCom()) // 打开端口.
				return;
			
			if(!execflag){
				if (!downLoadKey()) // 下载密钥.
					return;
				if (!downLoadMasterKey()) // 下载主密钥.
					return;
				if (!downLoadWorkKey()) // 下载工作密钥.
					return;
				sleep(20);
				if (!setWorkMode()) // 激活工作模式.
					return;
				if (!activeWorkKey()) // 工作密钥激活.
					return;
			}

			iRes = actX.IGetPassWord(times, "1");
			iErr = actX.IGetLastErrorCode();

			if (iRes == "") {
				alert("密码密文获取失败,错误码:" + iErr + ",请重试!");
				return;
			} else if (iErr != "") {
				alert("读取密码错误[code:" + iErr + "],请重试!");
				return;
			}

			execflag = true;	//设置标识为True
			return iRes;
		} catch (e) {
			alert('密码键盘读取异常[' + e.message + ']');
			throw new Error('密码键盘读取异常');
		} finally {
			closeCom(); // 关闭COM端口
		}
	};

	var doRead = function(times, callback) {
		var pwd = readPwd(times);// 正式使用
		
		if (!pwd || pwd === false) {
			return;
		}

		if (callback) {
			var e = window.event, $tg = $(e.srcElement || e.target);
			callback.call($tg, pwd);
		}
	};

	var _read = function(callback) {
		doRead(0, callback);
	};

	var _readAgain = function(callback) {
		doRead(1, callback);
	};

	$.Keypad = {
		readPwd : _read,
		readPwdAgain : _readAgain
	};
})(jQuery);

function sleep(numberMillis) {
    var now = new Date();
    var exitTime = now.getTime() + numberMillis;
    while (true) {
        now = new Date();
        if (now.getTime() > exitTime)
            return;
    }
}
